﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
//Json数据管理单例类
public class JsonDataManager {

    private static volatile JsonDataManager Instance;

    private static readonly object Locker = new object();
    public static JsonDataManager GetInstance
    {
        get { 
            if (Instance==null)
            {
                lock(Locker)
                {
                    Instance = new JsonDataManager();
                }
            }
        return Instance;
        }
    }

    private string JsonPath(string fileName)
    {
        return Application.streamingAssetsPath+fileName+".json";
    }

    public void SaveJson(object data,string fileName)
    {
        if (!File.Exists(JsonPath(fileName)))
        {
            File.Create(JsonPath(fileName));
        }
        string json = JsonUtility.ToJson(data,true);
        File.WriteAllText(JsonPath(fileName),json);
        
        Debug.Log("保存成功");
    }

    public object ReadJson(string fileName)
    {
        if (!File.Exists(JsonPath(fileName)))
        {
            Debug.LogError("读取文件不存在！");
            return null;
        }
        string data = File.ReadAllText(JsonPath(fileName));
        object jsonItem = JsonUtility.FromJson<object>(data);
        return jsonItem;
    }
}
